package com.sf;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LogParser {

    public static void main(String[] args) {
        String folderPath = "C:\\Users\\hcf\\work\\文档\\demo\\日志\\告警"; // 替换为你的文件夹路径
        String outputPath = "C:\\Users\\hcf\\work\\文档\\demo\\日志\\告警.txt"; // 替换为输出文件路径

        try {
            File folder = new File(folderPath);
            File[] listOfFiles = folder.listFiles((dir, name) -> name.toLowerCase().endsWith(".txt"));

            if (listOfFiles != null) {
                try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputPath))) {
                    writer.write("[");

                    for (File file : listOfFiles) {
                        if (file.isFile()) {
                            String logData = readFile(file.getAbsolutePath());
                            String jsonStr = extractJsonFromLog(logData);
//                            writer.write("File: " + file.getName() + "\n");
                            writer.write(jsonStr + "\n\n");
                        }
                    }
                    writer.write("]");

                }
            } else {
                System.out.println("文件夹中没有找到txt文件。");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 读取文件内容
    public static String readFile(String filePath) throws IOException {
        StringBuilder content = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                content.append(line).append("\n");
            }
        }
        return content.toString();
    }

    // 提取请求参数后的JSON字符串
    public static String extractJsonFromLog(String logData) {
        // 定义正则表达式以匹配请求参数后的 JSON 字符串
        String regex = "请求参数: (\\[\\[.*?\\]\\])";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(logData);

        StringBuilder result = new StringBuilder();
        while (matcher.find()) {
            // 提取 JSON 字符串
            String jsonStr = matcher.group(1);
            List<JSONObject> list  = new ArrayList<>();

            result.append(jsonStr).append(",").append("\n");
        }
        return result.toString();
    }
}
